<?php
namespace Admin\Controller;
use Think\Controller;
class ShopController extends CommonController {

    //首页商品列表
    public function index() {
        $keywords = I('keywords', '');
        $where['status'] = 0;
        $p = I('p', 1, 'intval');
        if($keywords) {
            $where['goods_sn|goods_name'] = ['like', '%'.$keywords.'%'];
        }

        $goods = D('Goods');
        $data = $goods->getGoodsList($where);

        $this->assign('list', $data['list']);
        $this->assign('count', $data['count']);
        $this->assign('p', $p);
        $this->display();
    }

    //添加修改商品
    public function edit() {
        $id = I('id', 0, 'intval');
        $goods = D('Goods');

        if (IS_POST) {
            if ($goods->create() === false) {
                $this->ajaxReturn(V(0, $goods->getError()));
            }

            if ($id > 0) {
                if($goods->where(['id'=>$id])->save() !== false) {
                    $this->ajaxReturn(V(1, '保存成功'));
                } else {
                    $this->ajaxReturn(V(0, '保存失败'));
                }
            } else {
                if ($goods->add()) {
                    $this->ajaxReturn(V(1, '保存成功'));
                } else {
                    $this->ajaxReturn(V(0, '保存失败'));
                }
            }
        } else {
            $info = $goods->field(true)->find($id);

            $this->assign('info', $info);
            $this->display();
        }
    }

    //删除商品
    public function delete() {
        $id = I('id', 0, 'intval');
        if(!$id) {
            $this->ajaxReturn(V(0, '参数错误'));
        }

        if(M('Goods')->where(['id'=>$id])->delete() !== false) {
            $this->ajaxReturn(V(1, '删除成功'));
        } else {
            $this->ajaxReturn(V(0, '删除失败'));
        }
    }

    //图片上传
    public function uploadImg() {
        $res = uploadImg();
        $this->ajaxReturn($res);
    }

    //删除图片
    public function deleteImg() {
        $img = I('img', '');
        if (!$img) {
            $this->ajaxReturn(V(0, '图片地址不能为空'));
        }
        $res = @unlink($img);
        if ($res == true) {
            $this->ajaxReturn(V(1, '删除成功'));
        } else {
            $this->ajaxReturn(V(1, '删除失败'));
        }
    }
}